package router

import (
	"fmt"
	"gitee.com/manoshi/go-util/conf"
	"gitee.com/manoshi/go-util/log"
	"gitee.com/manoshi/go-util/router/validator"
	"gitee.com/manoshi/go-util/util"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/render"
	"github.com/swaggo/files"
	"github.com/swaggo/gin-swagger"
	"net/http"
)

func InitGinEngine(canCors bool) *gin.Engine {
	gin.SetMode(gin.ReleaseMode)
	c := gin.New()
	if canCors {
		corsConfig := cors.DefaultConfig()
		if conf.AllowOrigin == nil || len(conf.AllowOrigin) == 0 {
			corsConfig.AllowAllOrigins = true
		} else {
			corsConfig.AllowOrigins = conf.AllowOrigin
		}
		corsConfig.AllowHeaders = []string{"*"}
		c.Use(cors.New(corsConfig))
	}
	//便于工具监测
	c.GET("/favicon.ico", func(c *gin.Context) {
		c.Render(http.StatusOK, render.String{})
	})
	//自定义验证器
	validator.RegisterValidate()
	if conf.Env == "dev" || conf.Env == "test" {
		//swagger
		c.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
		log.Info("swagger init success")
	}
	return c
}

func Run(c *gin.Engine) {
	portAddr := ""
	arg1 := util.Args(1)
	if arg1 == "" {
		portAddr = fmt.Sprintf(":%d", conf.HttpPort)
	} else {
		portAddr = fmt.Sprintf(":%s", arg1)
	}
	log.Info(fmt.Sprintf("web start in port%s", portAddr))
	err := c.Run(portAddr)
	if err != nil {
		panic(err)
	}
}
